﻿using System;
using System.Threading.Tasks;
using Missbot.Common;
using WebSocket4Net;

namespace Missbot.Service.WebSocket
{
    /// <summary>
    /// WebSocket客户端
    /// </summary>
    public class WSClient
    {
        private readonly WebSocket4Net.WebSocket client;
        private readonly Action<string>          OnMsgRecedCallBack;
        private readonly Action                  OnCloseCallBack;

        private static ILogSvc ILogSvc => AutofacSvc.Resolve<ILogSvc>();

        public WSClient(string url, Action<string> OnMsgRecedCallBack = null, Action OnCloseCallBack = null)
        {
            client                  =  new WebSocket4Net.WebSocket(url);
            client.MessageReceived  += OnMessageReceived;
            client.Closed           += OnClosed;
            this.OnMsgRecedCallBack =  OnMsgRecedCallBack;
            this.OnCloseCallBack    =  OnCloseCallBack;
        }
        
        /// <summary>
        /// 消息接收事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnMessageReceived(object sender, MessageReceivedEventArgs e)
        {
            var message = e.Message;
            ILogSvc.Log(message);
            OnMsgRecedCallBack(message);
        }

        /// <summary>
        /// 连接关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClosed(object sender, EventArgs e)
        {
            ILogSvc.Log("WS Closed.");
            OnCloseCallBack();
        }

        /// <summary>
        /// 创建连接
        /// </summary>
        /// <returns></returns>
        public async Task<bool> Connect()
        {
            if (client.State == WebSocketState.Open)
            {
                ILogSvc.Log("WS is already open.");
                return true;
            }

            await Task.Run(() => client.Open());
            await Task.Delay(1000);
            if (client.State != WebSocketState.Open)
            {
                ILogSvc.Log("WS Connet failed.");
                return false;
            }

            ILogSvc.Log("WS Conneted.");
            return true;
        }

        // 发送消息（异步）
        public async Task SendAsync(string msg)
        {
            await Task.Run(() => client.Send(msg));
        }
    }
}